package com.lpfy.dtxc.utils;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import androidx.core.app.ActivityCompat;

/**
 * @author: hanGuangHui
 * @data: 2024/3/4
 * @description:
 */
public class DeviceUtil {

    public static String getSerial(Context context){
        String serial = "";
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            serial = Build.SERIAL;
        } else {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE)
                    == PackageManager.PERMISSION_GRANTED) {
                serial =  Build.getSerial();
            }
        }
        if(serial.isEmpty() || serial.equals("unknown")){
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (context.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        serial = telephonyManager.getImei();
                    } else {
                        serial = telephonyManager.getDeviceId();
                    }
                }
            } else {
                serial = telephonyManager.getDeviceId();
            }
            if (TextUtils.isEmpty(serial)) {
                serial = Settings.System.getString(
                        context.getContentResolver(),
                        Settings.System.ANDROID_ID
                );
            }
        }
        return serial;
    }
}
